package com.sjzny.security;

import cn.hutool.core.util.StrUtil;
import com.sjzny.exception.CaptchaException;
import com.sjzny.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 根据SpringSecurity规范自定义过滤器
* 目的:判断用户输入的验证码是否正确
*   1.正确-放行
*   2.错误-运行认证失败的处理器（这个处理器需要自定义）
* */
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取用户请求地址
        String path = request.getRequestURI();

        //获取用户请求方式
        String method = request.getMethod();

        //判断验证码是否正确
        if(path.equals("/login") && method.equalsIgnoreCase("POST")) {
            //获取登录请求中携带的验证码ID
            String captchaId = request.getParameter("captchaId");
            //获取用户输入的验证码
            String captchaInput = request.getParameter("captchaInput");
            //获取redis中的验证码文本
            String captchaRedis = (String)redisUtil.get(captchaId);

            try {
                //判断验证码是否正确 - 如果用户没有输入验证码或者验证码错误就会抛出异常
                validate(captchaId, captchaInput,captchaRedis);
            }catch(CaptchaException e) {
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }

            //判断验证码是否正确
        }
        //放行
        filterChain.doFilter(request, response);
    }
    public void validate(String captchaId,String captchaInput,String captchaRedis){
        if(StrUtil.isBlank(captchaId) || StrUtil.isBlank(captchaInput)) {
            throw new CaptchaException("验证码不能为空");
        }

        if(!captchaInput.equalsIgnoreCase(captchaRedis)){
            throw new CaptchaException("验证码输入错误");
        }
    }
}
